package com.voice.server.publish;

import com.alibaba.fastjson.JSONObject;
import com.voice.core.utils.ResponseUtil;
import com.voice.core.DefaultClient;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.entity.HttpHeader;
import com.voice.server.auth.Authorization;
import com.voice.server.connection.SdkConnection;
import com.voice.server.enums.ResultEnum;
import com.wangjiacai.utils.utils.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component("/message/pub/device/authentication")
public class AuthenticationHandler implements PublishHandler<SdkConnection>{

    @Autowired
    private Map<String, Authorization> authorizationMap;
    @Autowired
    private DefaultClient defaultClient;

    @Override
    public void handle(Stream stream,StreamData streamData, SdkConnection connection){
        HttpHeader authHeader = JSONObject.parseObject(streamData.readAllData(), HttpHeader.class);
        String name=authHeader.get("name",String.class);
        Authorization authorization=authorizationMap.get(name);
        String userId;
        if((userId=authorization.authorization(authHeader))==null){
            this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.success("/message/pub/device/authentication",ResultVOUtil.error(ResultEnum.ILLEGAL_USERS)), null);
        }else {
            this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.success("/message/pub/device/authentication",ResultVOUtil.success((Object)userId)), null);
        }
    }
}
